function mouseMove() {
    const moveEle = document.querySelector('.move')
    const moveRangeEle = document.querySelector('.moveRange')
    const bigBox = document.querySelector('.bigBox')
    const bigPic = document.querySelector('.bigBox>img')
    //获取元素p的尺寸
    moveRangeEle.onmousemove = function (e) {
        //获取事件对象
        e = e || window.event
        //获取光标位置,并把p元素的光标点设置成中心
        let x = e.offsetX - moveEle.offsetWidth / 2
        let y = e.offsetY - moveEle.offsetHeight / 2
        //边界判断
        //左边界
        if (x < 0) {
            x = 0
        }
        //右边界
        if (x > moveRangeEle.offsetWidth - moveEle.offsetWidth) {
            x = moveRangeEle.offsetWidth - moveEle.offsetWidth
        }
        // 上边界
        if (y < 0) {
            y = 0
        }
        // 下边界
        if (y > moveRangeEle.offsetHeight - moveEle.offsetHeight) {
            y = moveRangeEle.offsetHeight - moveEle.offsetHeight
        }

        //获取移动的比例
        /**
         遮罩层移动距离        遮罩层
         ------------   =  ------------
         背景图片移动距离      放大镜

          背景图片移动距离 =  遮罩层移动距离*放大镜/遮罩层
       **/
        let moveX = x * bigBox.offsetWidth / moveEle.offsetWidth
        let moveY = y * bigBox.offsetHeight / moveEle.offsetHeight

        moveEle.style.top = y + 'px'
        moveEle.style.left = x + 'px'

        bigPic.style.top = -moveY + 'px'
        bigPic.style.left = -moveX + 'px'
    }
    //鼠标移入出现
    moveRangeEle.onmouseover = function () {
        moveEle.style.display = 'block'
        bigBox.style.display = 'block'
        //计算背景图比例
        /*计算背景图比例
           遮罩层mask            放大镜bigGlass
          ---------------   =   ------------------
           显示图片showbox        背景图bigPicBox
         
           背景图片bigpicbox = 放大镜bigGlass*显示图片showbox/遮罩层mask
        */
        bigPic.style.width = bigBox.offsetWidth * moveRangeEle.offsetWidth / moveEle.offsetWidth + 'px'
        bigPic.style.height = bigBox.offsetHeight * moveRangeEle.offsetHeight / moveEle.offsetHeight + 'px'


    }
    //鼠标移出隐藏
    moveRangeEle.onmouseout = function () {
        moveEle.style.display = 'none'
        bigBox.style.display = 'none'

    }
}

function clickPic() {
    const bigPic = document.querySelector('.bigBox>img')
    //构造函数
    function changePic(olliEle, ulliEle) {
        this.olliEle = olliEle
        this.ulliEle = ulliEle
    }
    changePic.prototype.change = function () {

        const productStr = localStorage.getItem('PRODUCTDETAIL')
        let details = JSON.parse(productStr) || []
        let showProduct = details.find(index => index = 2)
        //遍历li
        for (let i = 0; i < this.ulliEle.length; i++) {
            //获取当前对象
            let _this = this
            //清除所有样式
            this.ulliEle[i].onclick = function () {
                _this.clear()
                _this.olliEle[i].classList.add('active')
                _this.ulliEle[i].classList.add('addBorder')
                bigPic.setAttribute('src', `${showProduct.picture}`)
            }

        }

    }
    changePic.prototype.clear = function () {
        for (let i = 0; i < this.olliEle.length; i++) {

            this.olliEle[i].classList.remove('active')
            this.ulliEle[i].classList.remove('addBorder')

        }

    }
    const olliEle = document.querySelectorAll('ol>li')
    const ulliEle = document.querySelectorAll('ul>li')
    let changeObj = new changePic(olliEle, ulliEle)
    changeObj.change()


}



const goCartBtn = document.querySelector('.goCartBtn')
const goListBtn = document.querySelector('.goListBtn')
//跳转到购物车页面
function goCart() {
    goCartBtn.onclick = function () {
        location.href = './cart.html'
    }
}
//跳转到商品列表界面
function goList() {
    goListBtn.onclick = function () {
        location.href = './index.html'
    }
}


//显示商品详情信息
function showProductDetail() {
    //从localstorage获取数据
    const productStr = localStorage.getItem('PRODUCTDETAIL')
    let details = JSON.parse(productStr) || []

    let showProduct = details.find(index => index = 2)

    //显示左边大图
    const topPic = document.querySelector('.topPic')
    let str = `
        <li class="active"><img src="${showProduct.picture}" alt="图1"></li>
        <li><img src="${showProduct.picture}" alt="图2"></li>
        <li><img src="${showProduct.picture}" alt="图3"></li>
        <li><img src="${showProduct.picture}" alt="图4"></li>
    `
    topPic.innerHTML = str

    //显示左边下面的小图
    const ulEle = document.querySelector('ul')
    let ulStr = `
        <li><img src="${showProduct.picture}" alt="图1"></li>
        <li><img src="${showProduct.picture}" alt="图2"></li>
        <li><img src="${showProduct.picture}" alt="图3"></li>
        <li><img src="${showProduct.picture}" alt="图4"></li>
    `
    ulEle.innerHTML = ulStr
    const bigBox = document.querySelector('.bigBox')
    let bigStr = `
        <img src="${showProduct.picture}" alt="图1">
    `
    bigBox.innerHTML = bigStr

    //显示右边商品信息
    const productMsg = document.querySelector('.productMsg')
    let msgStr = `
    <h2>${showProduct.product}</h2>
    <p class="p">${showProduct.detail}</p>
    <div>价格<span>￥${showProduct.price}</span></div>
    <a class="shop" href="#">店铺：${showProduct.shop}</a>
    <button class="joinCart" data-index="${showProduct.id}">加入购物车</button>
    `
    productMsg.innerHTML = msgStr

}


/**
 * 添加购物车
 *   本质: 将商品数据添加到localStorage
 */
function addCart(products) {
    const containerEle = document.querySelector('.container')
    containerEle.addEventListener('click', function (e) {
        e = e || window.event //事件对象
        let target = e.target || e.srcElement // 事件目标对象
        if (target.getAttribute('class') == 'joinCart') {
            //1. 构造添加到购物车的商品数据
            let id = target.getAttribute('data-index')
            console.log(products)
            let product = products.find((item) => item.id == id)

            product = {
                ...product, //选中商品
                num: 1, //数量
                singlePrice: product.price, //单个商品总价
                state: false // 选中状态
            }

            //  2.1. 从localstorage取出商品数据,如果是第一次，没有返回 空数组
            let productStr = localStorage.getItem('CARTLIST')
            let carts = JSON.parse(productStr) || []
            // 3.遍历购物车商品数组， 判断添加的商品，在商品数组中是否已经存在，
            let newProduct = carts.find((item) => item.id == product.id)
            if (newProduct) {
                // 3.1如果已经存在，改变商品数量
                newProduct.num++
                newProduct.singlePrice = (newProduct.num * product.price).toFixed(2)
            } else {
                //3.2如果不存在，添加一项商品
                carts.push(product)
            }

            //  4. 已经添加数据的数组重新写回localstorage
            localStorage.setItem('CARTLIST', JSON.stringify(carts))

            alert('添加购物车成功!')
        }
    })
}

//获取后端数据
function getProducts() {
    ajaxPromise({
        method: 'get',
        url: 'http://10.7.171.143:3000/api/productlist'
    }).then(data => {
        if (data.resultCode == -1) {
            alert('用户名或密码错误！')
        } else {
            
            addCart(data)
        }
    })
}

getProducts()
showProductDetail()
mouseMove()
goCart()
goList()
clickPic()